from playwright.sync_api import Page, expect  # 导入同步API
import os
from datetime import datetime
from pathlib import Path

def take_screenshot(page: Page, name: str = "screenshot", folder: str = "./screenshots", 
                   full_page: bool = False, quality: int = 90) -> str:
    """
    截图并保存到指定文件夹，文件名包含时间戳
    
    Args:
        page: Playwright页面对象
        name: 截图文件名（不含扩展名）
        folder: 保存文件夹路径
        full_page: 是否截取整个页面
        quality: 截图质量（仅适用于JPEG格式）
    
    Returns:
        截图文件的完整路径
    """
    # 创建截图目录
    screenshot_dir = Path(folder)
    screenshot_dir.mkdir(parents=True, exist_ok=True)
    
    # 生成带时间戳的文件名
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"{name}_{timestamp}.png"
    screenshot_path = screenshot_dir / filename
    
    # 截图选项
    screenshot_options = {
        "path": str(screenshot_path),
        "full_page": full_page
    }
    
    # 截图
    page.screenshot(**screenshot_options)
    print(f"截图已保存到: {screenshot_path}")
    
    return str(screenshot_path)

def test_baidu(page:Page) -> None:  #fixture page 代表一个打开的窗口
    page.goto("https://www.baidu.com")
    page.goto("https://www.bilibili.com")

    page.go_back()  #页面的后退
    
    # 示例1: 普通截图
    # take_screenshot(page, name="baidu_homepage", folder="./screenshots")
    
    # 示例2: 全页面截图
    take_screenshot(page, name="baidu_fullpage", folder="./screenshots", full_page=True)
    
    # 示例3: 保存到不同文件夹
    # take_screenshot(page, name="baidu_test", folder="./test_results/screenshots")
    
    expect(page).to_have_title("百度一下，你就知道")   #断言标题是否正确
    print(f'=====执行成功=====')

def test_switch(page: Page) -> None:
    page.goto("https://www.baidu.com")
    page.goto("https://www.bilibili.com")
    take_screenshot(page, name="page11", folder="./screenshots")
    page.go_back(wait_until="networkidle")  # 页面的后退，等待网络空闲

    url = page.url
    assert "baidu" in url
    take_screenshot(page, name="page12", folder="./screenshots")
    # page.go_forward(wait_until="networkidle")  # 页面的前进，等待网络空闲
    take_screenshot(page, name="page13", folder="./screenshots")
    # page.reload(wait_until="networkidle")  # 页面的刷新，等待网络空闲
    take_screenshot(page, name="page14", folder="./screenshots")

    # expect(page).to_have_title("百度一下，你就知道")  # 断言标题是否正确
    print(f'=====执行成功=====')

def test_location(page: Page) -> None:
    # 元素定位
    page.goto("https://www.baidu.com")
    # 定位元素
    element = page.get_by_role("link", name="新闻")
    # element.fill("123")  #相当于输入框输入123
    # 断言元素是否存在
    expect(element).to_be_visible()


if __name__ == '__main__':
    # take_screenshot()
    # test_baidu()
    test_switch()
    # test_switch()
